package tix

trait WeakOrdered[T] {
  def <=(t: WeakOrdered[T]): Boolean

  def compare(t: WeakOrdered[T]) = WeakOrdered.compare(this, t)
}

object WeakOrdered {
  abstract class Status
  case object Less extends Status
  case object Equal extends Status
  case object Greater extends Status
  case object Uncomparable extends Status

  def compare[T](a: WeakOrdered[T], b: WeakOrdered[T]): Status = {
    val ab = a <= b
    val ba = b <= a
    if (ab && ba) return Equal
    if (!ab && !ba) return Uncomparable
    if (ab) return Less
    if (ba) return Greater
    throw new RuntimeException("deadcode")
  }
}

// -------------------------------------------------------------------------------------------------

/** A version ID must be serializable. */
abstract class Version extends Serializable with WeakOrdered[Version] {
  /** String representation of the version. */
  def toString(): String

  /** Weak order between versions. */
  override def <=(v: WeakOrdered[Version]): Boolean
}

class StringVersion(val version: String) extends Version {
  override def toString() = version

  override def <=(v: WeakOrdered[Version]): Boolean = {
    val sv = v.asInstanceOf[StringVersion]
    return version <= sv.version
  }
}

class StdVersion(val major: Int, val minor: Int, val rev: Int) extends Version {
  override def toString() = "%s.%s.%s".format(major, minor, rev)

  override def <=(v: WeakOrdered[Version]): Boolean = {
    val sv = v.asInstanceOf[StdVersion]
    if (major != sv.major) return major < sv.major
    if (minor != sv.minor) return minor < sv.minor
    return rev <= sv.rev
  }
}
